//
//  NSString+Category.m
//  Test
//
//  Created by eiop on 2021/7/27.
//

#import "NSString+Category.h"

@implementation NSString (Category)

- (NSMutableAttributedString *)convertArabicNumeralsForChineseNumerals:(BOOL)company {
    if (!self.length) {
        return nil;
    }
    NSString *resultString = @"";//拼接字符串，最终得到一个逗号分割开数字的字符串，例:1,23,456,7.89
    for (NSUInteger index = 0; index < self.length; index ++) {
        NSString *currentString = @"";//当前字符
        if (self.length > 0) {
            currentString = [self substringWithRange:NSMakeRange(index, 1)];
        }
        NSString *lastString = @"";//当前字符的上一个字符
        if (index > 0) {
            lastString = [self substringWithRange:NSMakeRange(index-1, 1)];
        }
        NSString *nextString = @"";//当前字符的下一个字符
        if (index < self.length-1) {
            nextString = [self substringWithRange:NSMakeRange(index+1, 1)];
        }
        //NSLog(@"上一个字符：%@ 当前字符：%@ 下一个字符：%@",currentString,lastString,nextString);
        
        BOOL isInt = NO;//用于记录当前字符是否符合浮点型条件
        if (index > 0) {
            if ([currentString isEqualToString:@"."]) {//判断当前字符是小数点，且上一个字符是整型，下一个字符也是整型
                if ([lastString isPureInt] && [nextString isPureInt]) {
                    isInt = YES;
                }
                if (!company) {//如果不计数字单位（个十百千万....），所有的小数点 . 都要转成汉字 点
                    isInt = YES;
                }
            }
        }
        if ([currentString isPureInt]) {//当前字符为整型情况下，可继续执行
            if (!resultString.length) {//为空的情况下，拼接当前字符串
                resultString = [NSString stringWithFormat:@"%@%@",resultString,currentString];
            }
        } else {
            if ([lastString isPureInt]){
                if (isInt) {//当前字符是小数点并且前后一个字符都是整型的情况下
                    NSString *lastObject = [resultString componentsSeparatedByString:@","].lastObject;//找到最后一个元素
                    if ([lastObject rangeOfString:@"."].location != NSNotFound) {//判断最后一个元素是否包含小数点，做如下的字符串拼接
                        resultString = [NSString stringWithFormat:@"%@,%@",resultString,nextString];////拼接逗号和下一个字符
                    }else{
                        resultString = [NSString stringWithFormat:@"%@%@%@",resultString,currentString,nextString];//拼接当前字符和下一个字符
                    }
                }else{
                    resultString = [NSString stringWithFormat:@"%@,",resultString];//当前字符不为整型，并且上一个字符是数字，拼接一个逗号将其分隔开
                }
            }
        }
        if ([nextString isPureInt] && !isInt) {//如果下一个字符是整型或者当前字符 符合浮点型条件
            resultString = [NSString stringWithFormat:@"%@%@",resultString,nextString];
        }
    }
    NSLog(@"拼接后的字符串：%@",resultString);
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self];
    NSMutableArray *numberArray = [NSMutableArray arrayWithArray:[resultString componentsSeparatedByString:@","]];
    for (NSString *numberString in numberArray) {//将得到的符合基本类型的数字组合，转成带单位的汉字
        if (numberString.length) {
            NSLog(@"转字符：%@",numberString);
            NSRange range = [attributedString.string rangeOfString:numberString];
            NSString *replaceString = [numberString translationArabicNumerals:company];
            [attributedString replaceCharactersInRange:range withString:replaceString];//根据字符串的位置替换原有的阿拉伯数字
            [attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(range.location, replaceString.length)];//给转换后的字加上下划线
        }
    }
    NSLog(@"转化后的字符串：%@",attributedString);
    return attributedString;
}

/// 将阿拉伯数字转换为中文数字
/// @param company 是否需要单位（个十百千万...）
- (NSString *)translationArabicNumerals:(BOOL)company {
    NSString *resultString = self;
    NSString *decimalString = @"";
    if ([self rangeOfString:@"."].location != NSNotFound) {//如果是小数点的话则需要分割开来，小数点前有单位，反之没有，resString始终保持整型，小数单独转换 拼接
        resultString = [self componentsSeparatedByString:@"."].firstObject;
        decimalString = [self componentsSeparatedByString:@"."].lastObject;
    }
    //准备一系列将要替换的元数据
    NSArray *arabicNumeralsArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",@"."];
    NSArray *chineseNumeralsArray = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零",@"点"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chineseNumeralsArray forKeys:arabicNumeralsArray];
    if (!company) {//不需要单位的情况下直接将阿拉伯数字转成中文数字
        NSString *chinese = self;
        for (id key in dictionary.allKeys) {
            if ([self rangeOfString:key].location != NSNotFound) {
                chinese = [chinese stringByReplacingOccurrencesOfString:key withString:dictionary[key]];
            }
        }
        return chinese;
    }
    NSArray *digitArray = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
    if (resultString.doubleValue < 20 && resultString.doubleValue > 9) {//如果处于10-20之间则是十位数
        if (resultString.doubleValue == 10) {
            return @"十";
        } else {
            NSString *subStr = [resultString substringWithRange:NSMakeRange(1, 1)];
            NSString *chinese = [NSString stringWithFormat:@"十%@",dictionary[subStr]];
            return chinese;
        }
    } else {//根据字符取相应的单位
        NSMutableArray *sumArray = [NSMutableArray array];
        for (int i = 0; i < resultString.length; i ++) {
            NSString *subString = [resultString substringWithRange:NSMakeRange(i, 1)];
            NSString *number = dictionary[subString];
            NSString *digit = digitArray[resultString.length-i-1];
            NSString *sum = [number stringByAppendingString:digit];
            if ([number isEqualToString:chineseNumeralsArray[9]]) {
                if ([digit isEqualToString:digitArray[4]] || [digit isEqualToString:digitArray[8]]) {
                    sum = digit;
                    if ([[sumArray lastObject] isEqualToString:chineseNumeralsArray[9]]) {
                        [sumArray removeLastObject];
                    }
                } else {
                    sum = chineseNumeralsArray[9];
                }
                if ([[sumArray lastObject] isEqualToString:sum]) {
                    continue;
                }
            }
            [sumArray addObject:sum];
        }
        NSString *sumString = [sumArray componentsJoinedByString:@""];
        NSString *chinese = [sumString substringToIndex:sumString.length-1];
        if (decimalString.length) {
            return [NSString stringWithFormat:@"%@点%@",chinese,[decimalString convertArabicNumeralsForChineseNumerals:NO]];
        }
        return chinese;
    }
}

/// 判断一个字符串是否为阿拉伯数字
- (BOOL)isPureInt {
    NSScanner *scan = [NSScanner scannerWithString:self];
    int val = 0;
    return [scan scanInt:&val] && [scan isAtEnd];
}

@end
